<template>
	<div class="answer_newQuestion_container">
		<div class="answer_newQuestion_title">{{title}}</div>
		<el-form ref="form" :model="form" :rules="rules" label-width="1.2rem">
			<el-form-item label="题目层级" prop="levelOptionId">
				<el-select class="select levelOption_select" v-model="form.levelOptionId" placeholder="请选择题目层级">
					<el-option v-for="item in levelOptions" :key="item.id" :label="item.label" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="" prop="periodOptionId">
				<el-select class="select levelOption_select" v-model="form.periodOptionId" placeholder="请选择">
					<el-option v-for="item in periodOptions" :key="item.childrenId" :label="item.childrenName" :value="item.childrenId">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="showfirstQuestionOption" label="" prop="firstQuestionOptionId">
				<el-select class="select levelOption_select" v-model="form.firstQuestionOptionId" placeholder="请选择" :disabled="firstQuestionOptions.length<=0">
					<el-option v-for="item in firstQuestionOptions" v-if="editOraginData.childrenId!=item.childrenId" :key="item.childrenId" :label="item.childrenName" :value="item.childrenId">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item v-if="showSecondQuestionOption" label="" prop="secondQuestionOptionId">
				<el-select class="select levelOption_select" v-model="form.secondQuestionOptionId" placeholder="请选择" :disabled="secondQuestionOptions.length<=0">
					<el-option v-for="item in secondQuestionOptions" v-if="editOraginData.childrenId!=item.childrenId" :key="item.childrenId" :label="item.childrenName" :value="item.childrenId">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="题目名称" prop="name">
				<el-input class="input_txt" v-model="form.name" :disabled="(this.form.levelOptionId >= 2 && this.firstQuestionOptions.length<=0) || (this.form.levelOptionId == 3 && this.secondQuestionOptions.length<=0)"></el-input>
			</el-form-item>
			<el-form-item v-if="showDesc" label="详细说明" prop="desc">
				<el-input type="textarea" :autosize="{ minRows: 4}" class="input_txt input_desc" v-model="form.desc" :disabled="(this.form.levelOptionId >= 2 && this.firstQuestionOptions.length<=0) || (this.form.levelOptionId == 3 && this.secondQuestionOptions.length<=0)"></el-input>
			</el-form-item>
			<el-form-item v-if="showUpload" label="上传附件">
				<el-upload class="upload-list" :action="uploadUrl" name="file" :headers="headers" :on-preview="handlePreview" :before-upload="beforeAvatarUpload" :on-remove="handleRemove" :before-remove="beforeRemove" multiple :limit="1" :on-change="handleChange" :on-exceed="handleExceed" :on-error="uploadError" :on-success="uploadSuccess" :disabled="(this.form.levelOptionId >= 2 && this.firstQuestionOptions.length<=0) || (this.form.levelOptionId == 3 && this.secondQuestionOptions.length<=0)">
					<el-button class="btn_normal" type="primary" :disabled="(this.form.levelOptionId >= 2 && this.firstQuestionOptions.length<=0) || (this.form.levelOptionId == 3 && this.secondQuestionOptions.length<=0)">
						<div class="upload_icon"></div>上传附件
					</el-button>
					<div slot="tip" v-if="form.hasFileUrl && form.hasFileUrl!=''" class="upload-icon-document"><i class="el-icon-document"></i>{{form.hasFileUrl}} <i class="el-icon-close" @click="deleteFile"></i></div>
					<div slot="tip" class="upload-desc">文件大小不超过100M,支持扩展名：rar,zip,doc,docx,pdf,jpg...</div>
				</el-upload>
			</el-form-item>
			<el-form-item>
				<el-button class="btn_sure" type="primary" @click="onSubmit('form')" :disabled="(this.form.levelOptionId >= 2 && this.firstQuestionOptions.length<=0) || (this.form.levelOptionId == 3 && this.secondQuestionOptions.length<=0)">确定</el-button>
				<el-button class="btn_cancle" @click="onCnacle">取消</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>
<script>
	var vm;
	export default {
		components: {},
		data: function() {
			var checkPeriodOptionsExist = (rule, value, callback) => {
				if(vm.periodOptions.length <= 0)
					return callback(new Error('无选项'));
				else {
					callback();
				}
			};
			var checkFirstOptionsExist = (rule, value, callback) => {
				if(vm.firstQuestionOptions.length <= 0)
					return callback(new Error('无选项'));
				else {
					callback();
				}
			};
			var checkSecondOptionsExist = (rule, value, callback) => {
				if(vm.secondQuestionOptions.length <= 0)
					return callback(new Error('无选项'));
				else {
					callback();
				}
			};
			return {
				headers: {
					// 'Content-Type': 'multipart/form-data',
					'token': tool.getItem(lsKey.token),
				},

				flag: 0, //0新建，1编辑
				editOraginData: { //编辑闯关题目时，题目原始信息
					level: 1,
					childrenId: "",
					childrenName: "",
					extDesc: "",
					isHasFile: false,
					hasFileUrl: "",
					periodOptionId: "",
					firstQuestionOptionId: "",
					secondQuestionOptionId: "",
				},

				title: "新建闯关题目",
				levelOptions: [{
					id: 1,
					label: "一级"
				}, {
					id: 2,
					label: "二级"
				}, {
					id: 3,
					label: "三级"
				}],
				showfirstQuestionOption: false,
				showSecondQuestionOption: false,
				showDesc: false,
				showUpload: false,
				uploadUrl: window.config.baseUrl + "/file/upload",
				periodOptions: [{
					"checkPointId": "1",
					"checkPointName": "筹备期",
					"honorId": "1",
					"honorName": "青铜"
				}, {
					"checkPointId": "2",
					"checkPointName": "建设期",
					"honorId": "2",
					"honorName": "白银"
				}, {
					"checkPointId": "3",
					"checkPointName": "启动期",
					"honorId": "3",
					"honorName": "黄金"
				}, {
					"checkPointId": "4",
					"checkPointName": "运营期",
					"honorId": "4",
					"honorName": "钻石"
				}, {
					"checkPointId": "5",
					"checkPointName": "腾飞期",
					"honorId": "5",
					"honorName": "王者"
				}],
				firstQuestionOptions: [],
				secondQuestionOptions: [],
				form: {
					evaTypeId: "",
					levelOptionId: 1,
					levelOptionLabel: "一级",
					periodOptionId: "",
					periodOptionLabel: "",
					firstQuestionOptionId: "",
					firstQuestionOptionLabel: "",
					secondQuestionOptionId: "",
					secondQuestionOptionLabel: "",
					name: '',
					desc: '',
					isHasFile: false,
					hasFileName: '',
					hasFileUrl: '',
				},
				rules: {
					name: [{
						required: true,
						message: '不能为空',
						trigger: 'blur'
					}, ],
					periodOptionId: [{
							validator: checkPeriodOptionsExist,
							trigger: 'change'
						},
						{
							required: true,
							message: '请选择',
							trigger: 'change'
						},
					],
					firstQuestionOptionId: [{
							validator: checkFirstOptionsExist,
							trigger: 'change'
						},
						{
							required: true,
							message: '请选择',
							trigger: 'change'
						},
					],
					secondQuestionOptionId: [{
							validator: checkSecondOptionsExist,
							trigger: 'change'
						},
						{
							required: true,
							message: '请选择',
							trigger: 'change'
						},
					]
				},
				// { name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }
				fileList: []
			}
		},
		compute: {
			// selectDisable:function(){
			//   return (this.form.levelOptionId >= 2 && this.firstQuestionOptions.length<=0) || (this.form.levelOptionId == 3 && this.secondQuestionOptions.length<=0);
			// }
		},
		watch: {
			'form.levelOptionId': function() {
				vm.$refs['form'].clearValidate();
				// console.log("form.levelOptionId" + vm.form.levelOptionId);
				var index = vm.levelOptions.findIndex(d => d.id === vm.form.levelOptionId);

				vm.form.levelOptionLabel = (index >= 0 ? vm.levelOptions[index] : "");

				//控制表单项显示状态
				switch(vm.form.levelOptionId) {
					case 1:
						{
							this.showPeriodQuestionOption = true;
							this.showfirstQuestionOption = false;
							this.showSecondQuestionOption = false;
							this.showDesc = false;
							this.showUpload = false;
							break;
						}
					case 2:
						{
							this.showfirstQuestionOption = true;
							this.showSecondQuestionOption = false;
							this.showDesc = false;
							this.showUpload = false;
							break;
						}
					case 3:
						{
							this.showfirstQuestionOption = true;
							this.showSecondQuestionOption = true;
							this.showDesc = true;
							this.showUpload = true;
							break;
						}
					default:
						{
							this.showfirstQuestionOption = false;
							this.showSecondQuestionOption = false;
							this.showDesc = false;
							this.showUpload = false;
							break;
						}
				}
				//切换层级时 清空当前表单信息

				this.onClearCurIputData(vm.form.levelOptionId);
				vm.$nextTick(function() {
					if(vm.flag == 0) {
						if(vm.periodOptions.length > 0)
							vm.form.periodOptionId = vm.periodOptions[0].childrenId;
					} else {
						//编辑
						if(vm.editOraginData.periodOptionId != "") {
							var index = vm.periodOptions.findIndex(d => d.childrenId === vm.editOraginData.periodOptionId);
							if(index >= 0)
								vm.form.periodOptionId = vm.editOraginData.periodOptionId;
							else
								vm.form.periodOptionId = vm.periodOptions[0].childrenId;
						}
					}

				});

			},
			'form.periodOptionId': function() { //改变题目所处阶段时
				// console.log("form.periodOptionId" + vm.form.periodOptionId);
				var index = vm.periodOptions.findIndex(d => d.childrenId === vm.form.periodOptionId);
				if(index >= 0)
					vm.form.periodOptionLabel = vm.periodOptions[index];
				else
					vm.form.periodOptionLabel = "";
				if(vm.form.levelOptionId >= 2 && vm.form.periodOptionId != "") {
					// console.log("form.periodOptionId********request" + vm.form.levelOptionId);
					api.questionChild({
						parentId: vm.form.periodOptionId,
						evaTypeId: vm.form.evaTypeId
					}).then(function(data) {
						vm.firstQuestionOptions = data.list;
						if(vm.flag == 0) {
							if(vm.firstQuestionOptions.length > 0)
								vm.form.firstQuestionOptionId = vm.firstQuestionOptions[0].childrenId;
							else {
								vm.form.firstQuestionOptionId = "";
								vm.secondQuestionOptions = [];
								vm.form.secondQuestionOptionId = "";
							}
						} else {
							//编辑状态下,默认为之前的选项
							if(vm.editOraginData.firstQuestionOptionId != "") {
								var index = vm.firstQuestionOptions.findIndex(d => d.childrenId === vm.editOraginData.firstQuestionOptionId);
								if(index >= 0)
									vm.form.firstQuestionOptionId = vm.editOraginData.firstQuestionOptionId;
								else {
									if(vm.firstQuestionOptions.length > 0)
										vm.form.firstQuestionOptionId = vm.firstQuestionOptions[0].childrenId;
									else {
										vm.form.firstQuestionOptionId = "";
										vm.secondQuestionOptions = [];
										vm.form.secondQuestionOptionId = "";
									}
								}
							} else {
								if(vm.firstQuestionOptions.length > 0)
									vm.form.firstQuestionOptionId = vm.firstQuestionOptions[0].childrenId;
								else {
									vm.form.firstQuestionOptionId = "";
									vm.secondQuestionOptions = [];
									vm.form.secondQuestionOptionId = "";
								}
							}
						}
					}).catch(function(error) {

						// console.log(error);
					});
				}
			},
			'form.firstQuestionOptionId': function() { //改变题目所处第一级别时
				// console.log("form.firstQuestionOptionId" + vm.form.firstQuestionOptionId);
				var index = vm.firstQuestionOptions.findIndex(d => d.childrenId === vm.form.firstQuestionOptionId);
				if(index >= 0)
					vm.form.firstQuestionOptionLabel = vm.firstQuestionOptions[index];
				else
					vm.form.firstQuestionOptionLabel = "";

				if(vm.form.levelOptionId >= 3 && vm.form.firstQuestionOptionId != "") {
					// console.log("form.firstQuestionOptionId********request" + vm.form.firstQuestionOptionId);
					api.questionChild({
						parentId: vm.form.firstQuestionOptionId,
						evaTypeId: vm.form.evaTypeId
					}).then(function(data) {
						vm.secondQuestionOptions = data.list;
						if(vm.flag == 0) {
							if(vm.secondQuestionOptions.length > 0)
								vm.form.secondQuestionOptionId = vm.secondQuestionOptions[0].childrenId;
							else
								vm.form.secondQuestionOptionId = "";
						} else {
							//编辑状态下,默认为之前的选项
							if(vm.editOraginData.secondQuestionOptionId != "") {
								var index = vm.secondQuestionOptions.findIndex(d => d.childrenId === vm.editOraginData.secondQuestionOptionId);
								if(index >= 0)
									vm.form.secondQuestionOptionId = vm.editOraginData.secondQuestionOptionId;
								else {
									if(vm.secondQuestionOptions.length > 0)
										vm.form.secondQuestionOptionId = vm.secondQuestionOptions[0].childrenId;
									else
										vm.form.secondQuestionOptionId = "";
								}
							} else {
								if(vm.secondQuestionOptions.length > 0)
									vm.form.secondQuestionOptionId = vm.secondQuestionOptions[0].childrenId;
								else
									vm.form.secondQuestionOptionId = "";
							}
						}
					}).catch(function(error) {

						// console.log(error);
					});
				}
			},
			'form.secondQuestionOptionId': function() { //改变题目所处第二级别时
				// console.log("form.secondQuestionOptionId" + vm.form.secondQuestionOptionId);
				var index = vm.secondQuestionOptions.findIndex(d => d.childrenId === vm.form.secondQuestionOptionId);
				if(index >= 0)
					vm.form.secondQuestionOptionLabel = vm.secondQuestionOptions[index];
				else
					vm.form.secondQuestionOptionLabel = "";
			}
		},
		methods: {
			handleRemove(file, fileList) {
				console.log(file, fileList);
				vm.fileList = fileList;
			},
			handlePreview(file) {
				console.log(file);
			},
			handleExceed(files, fileList) {
				this.$message.warning(`只能上传一个附件, 你已经上传了 ${files.length} 个文件`);
			},
			handleChange(file, fileList) {
				vm.fileList = fileList;
			},
			beforeRemove(file, fileList) {
				// return this.$confirm(`确定删除 ${ file.name } ?`);
			},
			beforeAvatarUpload(file) {
				// const isJPG = file.type === 'image/jpeg';
				const isLt100M = (file.size / 1024 / 1024) <= 100;

				// if (!isJPG) {
				//   this.$message.error('Avatar picture must be JPG format!');
				// }
				if(!isLt100M) {
					this.$message.error('上传文件大小超过最大值100MB!');
				}
				return isLt100M;
			},
			uploadSuccess: function(response, file, fileList) {
				console.log("上传文件成功response" + response);
				console.log("上传文件成功file" + file);
				console.log("上传文件成功fileList" + fileList);
				// response：即为后端传来的数据，这里我返回的是图片的路径
				// vm.fileList = fileList;
				if(response.status != "success") {
					this.$message.error('上传文件失败，错误码' + response.errorCode);
					fileList.pop();
					vm.fileList = fileList;
				}
			},
			uploadError: function(response, file, fileList) {

				console.log("上传文件失败response" + response);
				console.log("上传文件失败file" + file);
				console.log("上传文件失败fileList" + fileList);
			},
			onClearCurIputData: function(level) {
				// this.form.name = "";
				// this.form.desc = "";
				// this.form.isHasFile = false;
				// this.form.hasFileName = "";
				// this.form.hasFileUrl = "";
				this.form.periodOptionId = "";
				this.form.firstQuestionOptionId = "";
				this.form.secondQuestionOptionId = "";
				return;
				switch(level) {
					case 1:
						{
							this.form.name = "";
							this.form.desc = "";
							this.form.isHasFile = false;
							this.form.hasFileName = "";
							this.form.hasFileUrl = "";
							this.form.periodOptionId = 1;
							this.form.firstQuestionOptionId = 1;
							this.form.secondQuestionOptionId = 1;
							break;
						}
					case 2:
						{
							this.form.name = "";
							this.form.desc = "";
							this.form.isHasFile = false;
							this.form.hasFileName = "";
							this.form.hasFileUrl = "";
							this.form.periodOptionId = 1;
							this.form.firstQuestionOptionId = 1;
							this.form.secondQuestionOptionId = 1;
							break;
						}
					case 3:
						{
							this.form.name = "";
							this.form.desc = "";
							this.form.isHasFile = false;
							this.form.hasFileName = "";
							this.form.hasFileUrl = "";
							this.form.periodOptionId = 1;
							this.form.firstQuestionOptionId = 1;
							this.form.secondQuestionOptionId = 1;
							break;
						}
					default:
						{
							this.form.name = "";
							this.form.desc = "";
							this.form.isHasFile = false;
							this.form.hasFileName = "";
							this.form.hasFileUrl = "";
							this.form.periodOptionId = 1;
							this.form.firstQuestionOptionId = 1;
							this.form.secondQuestionOptionId = 1;
							break;
						}
				}
			},
			deleteFile: function() {
				vm.form.hasFileUrl = "";
			},
			onSubmit(formName) {
				vm.$refs[formName].validate((valid) => {
					if(valid) {
						if(vm.form.name == "") {
							vm.$message.error('题目名不能为空');
							return;
						}
						let parentId = 0;
						let level = 2;
						switch(this.form.levelOptionId) {
							case 1:
								{
									level = 2;
									parentId = this.form.periodOptionId;
									break;
								}
							case 2:
								{
									level = 3;
									parentId = this.form.firstQuestionOptionId;
									break;
								}
							case 3:
								{
									level = 4;
									parentId = this.form.secondQuestionOptionId;
									break;
								}
							default:
								{
									level = 2;
									parentId = 0;
									break;
								}
						}
						
						
						if(parentId === "") {
							vm.$message.error('父级题目未选择');
							return;
						}
						var attachmentFile = vm.fileList.length > 0 ? vm.fileList[0].response.data.url : "";
						if(attachmentFile == "")
							attachmentFile = vm.form.hasFileUrl;

						if(vm.flag == 0) {
							//新建
							// let formData = new FormData();
							// formData.append('titleName', vm.form.name);
							// formData.append('parentId', parentId);
							// formData.append('level', level);
							// formData.append('createUserId', JSON.parse(tool.getItem(lsKey.user)).userId);
							// if (vm.fileList.length > 0) {
							//   formData.append('remark', vm.fileList[0].name);
							//   formData.append('attachment', vm.fileList[0].url);
							// }

							var data = {
								'evaTypeId':  vm.form.evaTypeId,
								'titleName': vm.form.name,
								'parentId': parentId,
								'level': level,
								'createUserId': tool.getItem(lsKey.user, true).userId,
								'remark': level >= 4 ? vm.form.desc : "",
								'attachment': level >= 4 ? attachmentFile : "",
							};
							api.questionAddEdit(data).then(function(data) {
								tool.message({message: "题目新建成功", type:"success", showClose: true});
								vm.$emit('selectType', 1);
							}).catch(function(error) {
								vm.$message.error('添加失败！');
							});
						} else {
							//编辑
							var data = {
								'evaTypeId':  vm.form.evaTypeId,
								'titleName': vm.form.name,
								'parentId': parentId,
								'level': level,
								'createUserId': tool.getItem(lsKey.user, true).userId,
								'remark': level >= 4 ? vm.form.desc : "",
								'attachment': level >= 4 ? attachmentFile : "",
								'titleId': vm.editOraginData.childrenId,
							};
							api.questionAddEdit(data).then(function(data) {
								tool.message({message: "题目修改成功", type:"success", showClose: true});
								vm.$emit('selectType', 1);
							}).catch(function(error) {
								vm.$message.error('修改失败！');
							});
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			onCnacle: function() {
				this.$emit('selectType', 1);
			},
			init: function(oraginData) {
				//默认新建题目
				vm.title = "新建闯关题目";
				vm.flag = 0;
				//编辑题目
				if(oraginData.childrenId) {
					vm.title = "修改闯关题目";
					vm.flag = 1;
				}

				//获取第一级下拉选项
				api.questionChild({ parentId: 0, evaTypeId: oraginData.evaTypeId }).then(function(data) {
					vm.periodOptions = data.list;
					//新建
					if(vm.flag == 0) {
						vm.form.levelOptionId = 1;
						vm.form.periodOptionId = vm.periodOptions[0].childrenId;
						vm.form.evaTypeId = oraginData.evaTypeId;
						
					} else {
						//编辑
						vm.editOraginData = oraginData;
						vm.form.levelOptionId = "";
						vm.$nextTick(function() {
							vm.form.levelOptionId = oraginData.level;
							// vm.$nextTick(function() {
							//   vm.form.firstQuestionOptionId = data.firstQuestionOptionId;
							//   vm.$nextTick(function() {
							//     vm.form.secondQuestionOptionId = data.secondQuestionOptionId;
							//   })
							// });
						});
						vm.form.evaTypeId = oraginData.evaTypeId;
						vm.form.name = oraginData.childrenName;
						vm.form.desc = oraginData.extDesc;
						vm.form.hasFileUrl = oraginData.hasFileUrl;
					}
				})

			},
			close: function() {

			},

			curPeroidChange: function(data) {
				api.questionChild({
					parentId: data.childrenId,
					evaTypeId: vm.form.evaTypeId
				}).then(function(data) {
					vm.firstQuestions = data.list;
				}).catch(function(error) {

					// console.log(error);
				});
			},
			curFirstChange: function(data) {
				api.questionChild({
					parentId: data.childrenId,
					evaTypeId: vm.form.evaTypeId
				}).then(function(data) {
					vm.secondQuestions = data.list;
				}).catch(function(error) {

					// console.log(error);
				});
			}
		},
		mounted: function() {
			// vm.onClearCurIputData();
		},
		created: function() {
			vm = this;
		}
	}
</script>
<style lang="scss">
	.answer_newQuestion_container {
		.el-form {
			width: 8.6rem;
			margin: 0 auto;
		}
		.el-form-item__label {
			font-size: 0.2rem;
			color: #666666;
		}
		.el-input__inner {
			font-size: 0.22rem;
			color: #999999;
		}
		.input_desc {
			.el-input__inner {
				//height: 1rem;
			}
		}
		.el-upload-list__item-name {
			font-size: 0.2rem;
			color: #999999;
			line-height: 0.4rem;
		}
		.el-icon-upload-success.el-icon-circle-check {
			width: 0.22rem;
			height: 0.22rem;
			text-align: center;
			align-items: center;
		}
		.el-upload-list__item.is-success .el-upload-list__item-status-label {
			top: 0.1rem;
		}
		.el-upload-list__item .el-icon-close {
			top: 0.14rem;
		}
		.el-upload-list__item .el-progress {
			bottom: 0rem;
		}
		.el-progress-bar {
			vertical-align: bottom;
		}
	}
</style>
<style scoped src="@/style/answer_system/answer_question_add_edit.css"></style>